<template>
  <n-card :bordered="false" class="proCard">

    <n-space>
      <n-select v-model:value="selectOptionValue" :options="selectOption" style="width: 200px;"
        @update:value="handleUpdateselectOption" />
      <n-input v-model:value="search" type="text" placeholder="请输入姓名" style="width: 400px;" />
      <n-button type="warning" secondary strong @click="searchPerson">查找</n-button>
      <n-button type="info" secondary strong @click="search = null">重置</n-button>

    </n-space>
    <BasicTable :columns="columns" :request="loadDataTable"
      :row-key="(row: ListDataAboutTeacher | ListDataAboutStudent | ListDataAboutLabAdmin) => row.id" ref="actionRef"
      :actionColumn="actionColumn" @update:checked-row-keys="onCheckedRow" :scroll-x="1090">

      <template #tableTitle>
        <n-button type="primary" secondary @click="addTable" style="margin-top: 10px;">
          <template #icon>
            <n-icon>
              <PlusOutlined />
            </n-icon>
          </template>
          新建用户
        </n-button>
      </template>

      <template #toolbar>
        <n-space>
          <n-upload action="" accept=".excel .xlsx" :custom-request="customRequest"
            :show-file-list="false">
            <n-button type="info" secondary>上传 excel 文件</n-button>
          </n-upload>
        </n-space>
      </template>
    </BasicTable>

    <!-- 新建用户模态框 -->
    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" title="新建用户">
      <n-form :model="formParams" :rules="rules" ref="formRef" label-placement="left" :label-width="80" class="py-4">
        <n-form-item label="账号" path="">
          <n-input placeholder="请输入账号" v-model:value="formParams.account" />
        </n-form-item>
        <n-form-item label="姓名" path="">
          <n-input placeholder="请输入姓名" v-model:value="formParams.username" />
        </n-form-item>
        <n-form-item label="用户角色" path="">
          <n-select v-model:value="selectOptionValue" :options="selectOption" style="width: 200px;" />
        </n-form-item>
        <n-form-item label="专业" path="" v-if="selectOptionValue == 1">
          <n-input placeholder="请输入专业" v-model:value="formParams.major" />
        </n-form-item>
        <n-form-item label="班级名" path="" v-if="selectOptionValue == 1">
          <n-input placeholder="请输入班级名" v-model:value="formParams.class_name" />
        </n-form-item>
        <n-form-item label="职称" path="" v-if="selectOptionValue == 3 || selectOptionValue == 2">
          <n-input placeholder="请输入职称" v-model:value="formParams.pro_rank" />
        </n-form-item>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showModal = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
        </n-space>
      </template>
    </n-modal>

    <!-- 修改用户模态框 -->
    <!-- todo -->
  </n-card>
</template>

<script lang="ts" setup>
import { h, reactive, ref } from 'vue';
import { BasicTable, TableAction } from '@/components/Table';

import { getTableList, getTableListAboutStudent, getTableListAboutTeacher, getTableListAboutLabAdmin,getTableListAboutDiffernetPeopleApi, getTableListAboutselectByName, handleResetPasswordApi, uploadFileApi } from '@/api/table/list';
import { columnsAboutTeacher, ListDataAboutTeacher } from './columns';
import { columnsAboutStudent, ListDataAboutStudent } from './columns';
import { columnsAboutLabAdmin, ListDataAboutLabAdmin } from './columns'
import { PlusOutlined } from '@vicons/antd';
import { useRouter } from 'vue-router';
import { type FormRules, NButton, NInput } from 'naive-ui';


const columns = ref();

const search = ref()
const selectOptionValue = ref(3)
const selectOption = ref([
  {
    label: "实验员",
    value: 3,
  },
  {
    label: '老师',
    value: 2,
  },
  {

    label: '学生',
    value: 1
  },
])
//区分下拉框搜索或查询搜索
let select = 1


const handleUpdateselectOption = (value: any, option: any) => {
  select = 1
  reloadTable();
}

const rules: FormRules = {
  default: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入',
  },

};


const router = useRouter();
const formRef: any = ref(null);
const actionRef = ref();

const showModal = ref(false);
const formBtnLoading = ref(false);
const formParams = reactive({
  name: '',
  address: '',

  id: '',
  username: '',
  account: '',
  role: '',
  pro_rank: '',
  major: '',
  class_name: '',

});

const actionColumn = reactive({
  width: 220,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record: any) {
    return h(TableAction as any, {
      style: 'button',
      actions: [
        {
          label: '修改信息',
          onClick: handleModify.bind(null, record),
          type:'info',
          secondary:true,
          ifShow: () => {
            return true;
          },

        },
        {
          label: '删除用户',
          onClick: handleDelete.bind(null, record),
          type:'error',
          secondary:true,
          ifShow: () => {
            return true;
          },

        },
        {
          label: '重置密码',
          onClick: handleResetPassword.bind(null, record),
          type:'warning',
          secondary:true,
          ifShow: () => {
            return true;
          },

        },
      ],
    });
  },
});


function addTable() {
  showModal.value = true;
}
//页数
const pageNum = ref()
const pageSize = ref()

const loadDataTable = async (res: any) => {

  pageNum.value = res.page; //当前页码  
  pageSize.value = res.pageSize; //每页显示的条数

  //设置表格表头
  if (selectOptionValue.value == 1) {
    columns.value = columnsAboutStudent
  } else if (selectOptionValue.value == 2) {
    columns.value = columnsAboutTeacher;
  } else if (selectOptionValue.value == 3) {
    columns.value = columnsAboutLabAdmin;
  }

  //设置表格体
  if (select == 1) {
    //按下拉框查询选项 接口都一样的
    return await getTableListAboutDiffernetPeopleApi({ ...res, "role": selectOptionValue.value, "pageNum": pageNum.value });
  } else if (select == 2) {
    //按姓名查询
    console.log(res, pageNum)
    return await getTableListAboutselectByName({ ...res, "role": selectOptionValue.value, "pageNum": pageNum.value, "username": search.value });
  }
};

function onCheckedRow(rowKeys: any) {
  console.log(rowKeys);
}


function confirmForm(e: { preventDefault: () => void; }) {
  e.preventDefault();
  formBtnLoading.value = true;
  formRef.value.validate((errors: any) => {
    if (!errors) {
      window['$message'].success('新建成功');
      setTimeout(() => {
        showModal.value = false;
        reloadTable();
      });
    } else {
      window['$message'].error('请填写完整信息');
    }
    formBtnLoading.value = false;
  });
}
function handleResetPassword(record: Recordable) {

  handleResetPasswordApi({ ...record })

}

function handleDelete(record: Recordable) {
  console.log('点击了删除', record);
  window['$message'].info('点击了删除');
}

function handleModify(record: Recordable) {
  console.log('点击了修改', record);
  window['$message'].info('点击了修改');
}


function reloadTable() {
  actionRef.value.reload();
}

function searchPerson() {

  select = 2

  console.log("selectOptionValue:", selectOptionValue.value, "search", search.value)

  reloadTable()

}


//批量导入
async function customRequest({ file , data , }) {

  const formData = new FormData();

  if (data) {
    Object.keys(data).forEach((key) => {
      formData.append(
        key,
        data[key]
      );
    });


  }

  formData.append("file", file.file);

  await uploadFileApi({ data: formData })

  reloadTable()
}



</script>

<style lang="less" scoped></style>
